package com.wpx.log.core.handler.param;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;

import org.springframework.stereotype.Component;

import com.wpx.log.core.LogContext;
import com.wpx.log.core.LogRequestContext;
import com.wpx.log.core.module.LogFile;
import com.wpx.log.core.module.LogParam;

@Component
public class ILogMultipartParamTypePolicy implements ILogParamTypePolicy {

	@Override
	public String type() {
		return "multipart/form-data";
	}

	@Override
	public void parseParam(LogContext logContext, LogRequestContext logRequestContext, Field logField, final List<LogParam> params) {

		HttpServletRequest request = logRequestContext.getHttpServletRequest();
	
		try {
			Collection<Part> parts = request.getParts();
			for (Part part : parts) {
				LogParam param;
				if(part.getSubmittedFileName() != null) {
					String fileName = logContext.getLogservice().saveFile(part.getInputStream(), part.getSubmittedFileName());
					param = new LogParam(part.getName(), fileName, LogParam.TYPE_FILE);
				}else {
					byte[] bytes = new byte[(int) part.getSize()];
					part.getInputStream().read(bytes);
					param = new LogParam(part.getName(), new String(bytes), LogParam.TYPE_BASE);
				}
				
				boolean addEd = false;
				for (LogParam p : params) {
					if(p.getName().equals(param.getName())) {
						p.addValue(param.getValue().get(0));
						addEd = true;
					}
				}
				
				if(addEd == false) {
					params.add(param);
				}
			}
		} catch (IOException | ServletException e) {
			e.printStackTrace();
		}
		
	}

}
